import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/login_entity.dart';
import 'package:wanxiang_app/pages/login/agreement.dart';
import 'package:wanxiang_app/pages/login/registe.dart';
import 'package:wanxiang_app/utils/tabChangeEvent.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/config_entity.dart';
import '../../bean/msg_log_entity.dart';
import '../../bean/simple_entity.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/account_textField2.dart';
import '../../widgets/agreement_dialog.dart';
import '../../widgets/simple_dialog.dart';
import '../index.dart';
import 'forget.dart';
import 'login_code.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';
import 'package:crypto/crypto.dart';
class LoginController extends GetxController{

  @override
  void onInit() {
    super.onInit();
  }
  @override
  void onClose() {
    super.onClose();
  }

  bool checked = false;
  String mobile='';
  String codeOrPsw='';
  String nickname = '';
  bool showNick = false;
  changeCheck(){
    checked= !checked;
    update();
  }

  void _doLogin(){
    if(!checked){
      showDialog(context: mContext, builder: (BuildContext context1) {
        return MyAgreemnentDialog(callBack: (String content) {
          if(content == 'cancel'){
            Navigator.pop(context1);
          }else if(content == 'sure'){
            checked = true;
            Navigator.pop(context1);
            update();
          }
        },
          cancelText: '拒绝',
          sureText: "已阅读并同意",
        );
      });
      return;
    }
    if(mobile.isEmpty){
      ToastUtil.show('请输入账号');
      return;
    }
    if(codeOrPsw.isEmpty){
      ToastUtil.show('请输入密码');
      return;
    }
    if(showNick && nickname.isEmpty){
      ToastUtil.show('请输入昵称');
      return;
    }
    DioManager.getInstance().post(ServiceUrl.login,{
      'login_way':'1',
      'userName':mobile,
      'password':codeOrPsw,
    'nick_name':nickname
    }, (data) async {
      var map = jsonDecode(data);
      LoginEntity bannerEntity = LoginEntity.fromJson(map);
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code == 200){
        var map2 = map['data'];
        UserUtil.saveUSER2(jsonEncode(map2).toString());
        _nimLogin();
      }else{
        if(bannerEntity.code==202){
          showNick = true;
          update();
        }

      }

    }, (error) {
      ToastUtil.show(error);
    });
  }
  late BuildContext mContext ;

  _nimLogin() async{
    String md5Str =  md5
        .convert(utf8.encode(UserUtil.getUSER()!.userName))
        .toString()
        .toUpperCase();
    final loginResult = await NimCore.instance.authService.login(NIMLoginInfo(
      account: UserUtil.getUSER()!.userName,
      token:md5Str,
      //authType: NIMAuthType.authTypeDynamic,
    ));
    if( loginResult.isSuccess){
    }
    // Get.back();
    // tabbarEventBus.fire(TabChangedEvent(-1));
    // Get.offAll(()=>IndexPage());
    tabbarEventBus.fire(TabChangedEvent(2000));
    Get.back(result:true);
  }

}
class LoginPage extends GetView<LoginController>  {
  late LoginController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<LoginController>(() => LoginController());
    controller = Get.find();
    context = context1;
    controller.mContext= context1;
    return GetBuilder<LoginController>(
      builder: (_){
        return  Scaffold(
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
              child: _content()
          ) ,
        );
      },
    )
    ;

  }

  Widget _content() {
    return Container(
      padding: EdgeInsets.only(left: 20.w, right: 20.w),
      decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/login_bg.png'),
            fit: BoxFit.fill,
          )
      ),
      child: Stack(
        children: [
          Column(
            children: [
              SizedBox(
                height: MediaQueryData.fromWindow(window).padding.top + 21.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [

                  InkWell(
                      onTap: (){
                        Get.back();
                      },
                      child:  Image.asset(Constant.IMG_BASE+'ic_back.png',width: 15.w,height: 15.h,)
                  ),

                  // InkWell(
                  //     onTap: (){
                  //       Get.to(()=>LoginCodePage(),preventDuplicates:false);
                  //     },
                  //     child:   Text(
                  //       '验证码登录',
                  //       style: TextStyle(color: Color(0xFF333333), fontSize: 15.sp),
                  //     )
                  // )

                ],
              ),
              SizedBox(
                height: 23.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    'HELLO!',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                        color: Color(0xFF333333),
                        fontSize: 29.sp,
                        fontWeight: FontWeight.w600),
                  )
                ],
              ),
              SizedBox(
                height: 22.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    '欢迎来到淘号阁',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: 21.sp,
                    ),
                  )
                ],
              ),
              Container(
                margin: EdgeInsets.only(
                  top: 60.h,
                ),
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  hitText: '请输入手机号',
                  inputColor: 0xFFFFFFFF,
                  icon: 'assets/images/login_account.png',
                  contentStrCallBack: (content) {
                    controller.mobile = content;

                  }, key: ValueKey('account'),
                ),
              ),
              Container(
                margin: EdgeInsets.only(
                  top: 22.h,
                ),
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  pwd:true,
                  hitText: '请输入密码',
                  icon: 'assets/images/login_psw.png',
                  contentStrCallBack: (content) {
                    controller.codeOrPsw = content;
                  }, key: ValueKey('psw'),
                ),
              ),

              SizedBox(
                height: 19.h,
              ),
              controller.showNick?
              Container(
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  hitText: '请输入昵称',
                  icon: 'assets/images/nick.png',
                  contentStrCallBack: (content) {
                    controller.nickname = content;

                  }, key: ValueKey('account'),
                ),
              ):Container(),
              SizedBox(
                height: 19.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                      onTap: (){
                        // Get.to(()=>LoginCodePage(),arguments: 0,preventDuplicates:false)?.then((value) {
                        //   if(value){
                        //     Get.back();
                        //   }
                        // });
                        Get.back();
                      },
                      child: Text(
                        '验证码登录',
                        style: TextStyle(color: Color(0xFF333333), fontSize: 13.sp),
                      )
                  )
                  ,

                  InkWell(
                      onTap: (){
                        Get.to(()=>ForgetPage(),arguments: 1,preventDuplicates:false);
                      },
                      child: Text(
                        '忘记密码',
                        style: TextStyle(color: Color(0xFF333333), fontSize: 13.sp),
                      )
                  )
                  ,
                ],
              ),
              SizedBox(height: 150.h,),

              InkWell(
                  onTap: (){
                    controller._doLogin();
                  },
                  child:  Container(
                    alignment: Alignment.center,
                    width: 300.w,
                    height: 44.h,
                    decoration: BoxDecoration(
                        color: Color(0xFF007BE5),
                        borderRadius: BorderRadius.circular(6.r)),
                    child: Text(
                      '登录',
                      style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    ),
                  )
              )
              ,
              SizedBox(
                height: 16.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                      value: controller.checked,
                      onChanged: (value) {
                        controller.changeCheck();
                      }),
                  Text(
                    '阅读并同意',
                    style: TextStyle(
                        color: Color(0xFF666666), fontSize: 13.sp),
                  ),
                  InkWell(
                      onTap: () {
                        Get.to(()=>AgreementPage(),arguments: '用户协议');
                      },
                      child: Text(
                        '《用户协议》',
                        style: TextStyle(
                            color: Color(0xFF007BE5), fontSize: 13.sp),
                      )),
                  InkWell(
                      onTap: () {
                        Get.to(()=>AgreementPage(),arguments: '隐私协议');
                      },
                      child: Text(
                        '《隐私协议》',
                        style: TextStyle(
                            color: Color(0xFF007BE5), fontSize: 13.sp),
                      )),
                ],
              )


            ],
          ),
        ],
      ),
    );
  }
}
